package com.shy.pet.controller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.shy.pet.common.BaseContext;
import com.shy.pet.common.R;
import com.shy.pet.entity.Users;
import com.shy.pet.service.UsersService;

import jakarta.servlet.http.HttpServletRequest;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.DigestUtils;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;




@Slf4j
@RestController
@RequestMapping("/users")
public class UsersController {
    @Autowired
    private UsersService usersService;
    //用户登录
    @PostMapping("/login")
    public R<Users> login(HttpServletRequest request, @RequestBody Users users) {
        //将页面提交的密码进行md5加密处理
        String password = users.getPassword();
         password = DigestUtils.md5DigestAsHex(password.getBytes());
         //根据页面提交的用户名查询数据库
        LambdaQueryWrapper<Users> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(Users::getUsername, users.getUsername());
        Users emp = usersService.getOne(queryWrapper);

        //如果没有查询到返回失败
        if (emp == null) {
            return R.error("登录失败");
        }
        //如果查询到则判断密码是否正确
        if (!emp.getPassword().equals(password)) {
            return R.error("登录失败");
        }
        //登录成功将用户id存入session
        request.getSession().setAttribute("users", emp.getUserId());
        //返回成功信息
        return R.success(emp);
    }

    //退出
    @PostMapping("/logout")
    public R<String> logout(HttpServletRequest request) {
        //清理session中保存的当前登录用户id
        request.getSession().removeAttribute("users");
        return R.success("退出成功");
    }

    //注册
    @PostMapping("/register")
    public R<String> register(HttpServletRequest request, @RequestBody Users users) {
        // 检查用户名是否为空
        if (users.getUsername() == null || users.getUsername().isEmpty()) {
            return R.error("用户名不能为空");
        }
        // 查询有没有重复用户名在数据库里
        LambdaQueryWrapper<Users> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(Users::getUsername, users.getUsername());
        if (usersService.getOne(queryWrapper) != null) {
            return R.error("用户名重复");
        }
        // 注册
        usersService.save(users);
        request.getSession().setAttribute("users", users.getUserId());
        return R.success("注册成功");
    }


}

